<template>
	<view class="launch-event">
		<!-- #ifndef  H5 -->
		<u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent" style="background-color: #f5f5f5">
			<u-navbar :is-back="true" title="发起活动" :title-bold="true" :is-fixed="false" :border-bottom="false"
				title-color="#000000"
				:background="{ background: '#f5f5f5' }" class="custom-navbar">
				<view slot="right" class="navbar-right">
					<view class="nav-icon" @click="goToActivityList">
						<text class="nav-text">我的活动</text>
					</view>
				</view>
			</u-navbar>
		</u-sticky>
		<!-- #endif -->
		
		<!-- 进度指示器 -->
		<view class="progress-bar">
			<view v-for="(step, index) in stepsList" :key="index" class="progress-step" :class="{ 'active': current >= index, 'completed': current > index }">
				<view class="step-number">{{ index + 1 }}</view>
				<view class="step-title">{{ step.name }}</view>
			</view>
		</view>

		<!-- 步骤内容 -->
		<view class="step-content">
			<StepOne 
				v-if="current === 0" 
				:activityId="activityId"
				:activityData="activityData"
				:formCache="formCache.stepOne"
				@next="handleStepOneNext"
				@created="handleActivityCreated"
				@updateData="updateActivityData"
				@updateCache="(data) => updateFormCache('stepOne', data)"
			/>
			<StepTwo 
				v-if="current === 1" 
				:activityId="activityId"
				:activityData="activityData"
				:formCache="formCache.stepTwo"
				@next="handleStepTwoNext"
				@prev="prevStep"
				@updateData="updateActivityData"
				@updateCache="(data) => updateFormCache('stepTwo', data)"
			/>
			<StepThree 
				v-if="current === 2" 
				:activityId="activityId"
				:activityState="activityState"
				:activityData="activityData"
				@prev="prevStep"
				@jump="jumpToStep"
				@restart="restartProcess"
			/>
			<StepFour 
				v-if="current === 3" 
				:activityId="activityId"
				:activityState="activityState"
				:activityData="activityData"
				@restart="restartProcess"
			/>
		</view>
	</view>
</template>

<script>
import StepOne from './components/StepOne'
import StepTwo from './components/StepTwo'
import StepThree from './components/StepThree'
import StepFour from './components/StepFour'
import store from '@/store'
import { activityDetail } from '@/api/launchevent'

export default {
	components: {
		StepOne,
		StepTwo, 
		StepThree,
		StepFour
	},
	
	data() {
		return {
			current: 0,
			stepsList: [
				{ name: '活动信息' },
				{ name: '发布设置' },
				{ name: '审核状态' },
				{ name: '发布完成' }
			],
			activityId: null,
			activityState: 0, // 0-草稿 1-审核中 2-审核通过 -1-审核失败
			activityData: {}, // 活动数据缓存
			formCache: {
				stepOne: {},
				stepTwo: {}
			},
			// 自动保存定时器
			autoSaveInterval: null
		}
	},
	
	onLoad(options) {
		if (!this.checkLogin()) return;
		
		// 获取路由参数
		const routeQuery = this.$Route.query || options || {};
		console.log('页面加载参数:', routeQuery);
		this.activityId = routeQuery?.id || null;
		console.log(this.activityId ? `编辑活动ID: ${this.activityId}` : '新建活动');
		
		if (this.activityId) {
			// 编辑活动：先加载活动详情，再根据状态调整步骤
			console.log('加载活动详情')
			this.loadActivityDetail();
		} else {
			// 新建活动：先清除缓存，确保从第一步开始
			this.clearCache();
			// 然后尝试从缓存恢复数据（但步骤保持为0）
			this.loadFromCacheForNewActivity();
			// 初始化页面状态
			this.initializePageState();
		}
		
		// 启动自动保存
		this.startAutoSave();
	},
	
	onUnload() {
		// 清理自动保存定时器
		if (this.autoSaveInterval) {
			clearInterval(this.autoSaveInterval);
			this.autoSaveInterval = null;
		}
		
		// 页面卸载时保存缓存
		this.saveToCache();
		
		console.log('页面卸载，已清理资源');
	},
	
	methods: {
		checkLogin() {
			const token = store.getters.token;
			if (!token) {
				uni.showModal({
					title: '提示',
					content: '请先登录后再发起活动',
					showCancel: false,
					success: () => {
						uni.redirectTo({
							url: '/pages/login/login?redirect=/bundle/launchevent/launchevent'
						});
					}
				});
				return false;
			}
			return true;
		},
		
		async loadActivityDetail() {
			try {
				const res = await activityDetail({ id: this.activityId });
				this.activityState = res.state;
				this.activityData = res;
				
				// 编辑活动时，只恢复表单缓存数据，不恢复活动ID和状态
				this.loadFromCacheForEdit();
				this.adjustStepByState();
			} catch (e) {
				console.error('加载活动详情失败:', e);
				uni.showToast({ title: '加载失败', icon: 'none' });
			}
		},
		
		adjustStepByState() {
			switch (this.activityData.state) {
				case 0: // 草稿状态 - 从第一步开始
					this.current = 0; // StepOne
					break;
				case 1: // 待审核
					this.current = 2; // StepThree
					break;
				case 2: // 审核通过
					this.current = 3; // StepFour
					break;
				case -1: // 审核失败
					this.current = 2; // StepThree
					break;
				default:
					this.current = 0;
			}
		},
		
		handleActivityCreated(newId) {
			console.log('活动创建成功，ID:', newId)
			this.activityId = newId;
			// 新创建的活动状态为草稿状态
			this.activityState = 0;
			// 不需要重新加载详情，直接进入下一步
			this.nextStep();
		},
		
		handleStepJump(step) {
			this.jumpToStep(step);
		},
		
		// 步骤控制
		nextStep() {
			console.log('下一步，当前步骤:', this.current);
			
			if (this.current < this.stepsList.length - 1) {
				// 保存当前步骤的缓存
				this.saveToCache();
				
				this.current++;
				
				// 再次保存缓存，确保步骤状态被保存
				this.saveToCache();
				
				uni.showToast({
					title: `进入${this.stepsList[this.current].name}`,
					icon: 'success',
					duration: 1000
				});
			}
		},

		prevStep() {
			console.log('上一步，当前步骤:', this.current);
			
			if (this.current > 0) {
				// 保存当前步骤的缓存
				this.saveToCache();
				
				this.current--;
				
				// 再次保存缓存，确保步骤状态被保存
				this.saveToCache();
			}
		},

		jumpToStep(step) {
			if (step >= 0 && step < this.stepsList.length) {
				// 保存当前步骤的缓存
				this.saveToCache();
				
				this.current = step;
				
				// 再次保存缓存，确保步骤状态被保存
				this.saveToCache();
			}
		},

		// 处理取消操作
		handleCancel() {
			uni.showModal({
				title: '确认取消',
				content: '取消后将丢失当前填写的信息，确定要取消吗？',
				success: (res) => {
					if (res.confirm) {
						// 清除草稿
						this.clearCache();
						// 返回上一页
						uni.navigateBack();
					}
				}
			});
		},

		// 重新开始流程
		restartProcess() {
			console.log('重新开始发起活动流程');
			
			// 清除所有缓存数据
			this.clearCache();
			
			// 重置所有状态
			this.current = 0;
			this.activityId = null;
			this.activityState = 0;
			this.activityData = {};
			this.formCache = { stepOne: {}, stepTwo: {} };
			
			// 保存重置后的状态
			this.saveToCache();
			
			uni.showToast({
				title: '已重置，可以发起新活动',
				icon: 'success',
				duration: 1500
			});
		},

		// 启动自动保存
		startAutoSave() {
			// 每30秒自动保存一次
			this.autoSaveInterval = setInterval(() => {
				this.saveToCache();
			}, 30000);
		},

		// 初始化页面状态
		initializePageState() {
			console.log('页面状态初始化完成');
		},

		// 自动保存草稿（保持向后兼容）
		autoSave() {
			this.saveToCache();
		},

		// 加载草稿（保持向后兼容）
		loadDraft() {
			this.loadFromCache();
		},

		// 清除草稿（保持向后兼容）
		clearDraft() {
			this.clearCache();
		},
		
		// 缓存管理
		saveToCache() {
			try {
				const cacheData = {
					current: this.current,
					activityId: this.activityId,
					activityState: this.activityState,
					activityData: this.activityData,
					formCache: this.formCache,
					timestamp: Date.now()
				};
				
				// 使用JSON.stringify检测循环引用
				const jsonString = JSON.stringify(cacheData, (key, value) => {
					// 处理可能的循环引用
					if (typeof value === 'object' && value !== null) {
						// 如果是spec_value_list，进行深拷贝以避免循环引用
						if (key === 'spec_value_list' || key === 'priceList' || key === 'activitySpecs') {
							return JSON.parse(JSON.stringify(value));
						}
					}
					return value;
				});
				
				uni.setStorageSync('launchevent_cache', JSON.parse(jsonString));
				console.log('缓存保存成功');
			} catch (error) {
				console.error('缓存保存失败，存在循环引用或其他错误:', error);
				
				// 如果出现循环引用，尝试保存简化版本
				try {
					const simplifiedCache = {
						current: this.current,
						activityId: this.activityId,
						activityState: this.activityState,
						activityData: this.activityData,
						formCache: {
							stepOne: this.formCache.stepOne || {},
							stepTwo: {
								// 只保存基本数据，避免循环引用
								shareType: this.formCache.stepTwo?.shareType,
								shareRatio: this.formCache.stepTwo?.shareRatio,
								shareFixed: this.formCache.stepTwo?.shareFixed,
								implementType: this.formCache.stepTwo?.implementType,
								implementRatio: this.formCache.stepTwo?.implementRatio,
								implementFixed: this.formCache.stepTwo?.implementFixed,
								isCouponEnabled: this.formCache.stepTwo?.isCouponEnabled,
								// 对于复杂对象，进行深拷贝
								specList: this.formCache.stepTwo?.specList ? JSON.parse(JSON.stringify(this.formCache.stepTwo.specList)) : [],
							}
						},
						timestamp: Date.now()
					};
					
					uni.setStorageSync('launchevent_cache', simplifiedCache);
					console.log('简化版缓存保存成功');
				} catch (fallbackError) {
					console.error('简化版缓存保存也失败:', fallbackError);
				}
			}
		},

		loadFromCache() {
			try {
				const cacheData = uni.getStorageSync('launchevent_cache');
				if (cacheData && cacheData.timestamp) {
					// 检查缓存是否过期（24小时）
					const now = Date.now();
					const cacheAge = now - cacheData.timestamp;
					const maxAge = 24 * 60 * 60 * 1000; // 24小时

					if (cacheAge < maxAge) {
						this.current = cacheData.current || 0;
						this.activityId = cacheData.activityId;
						this.activityState = cacheData.activityState || 0;
						this.activityData = cacheData.activityData || {};
						this.formCache = cacheData.formCache || { stepOne: {}, stepTwo: {} };
					} else {
						// 缓存过期，清除
						this.clearCache();
					}
				}
			} catch (e) {
				console.error('加载缓存失败:', e);
			}
		},

		clearCache() {
			uni.removeStorageSync('launchevent_cache');
			this.current = 0;
			this.activityId = null;
			this.activityState = 0;
			this.activityData = {};
			this.formCache = { stepOne: {}, stepTwo: {} };
		},

		handleStepOneNext() {
			// StepOne组件已经通过@updateData事件更新了数据
			this.nextStep();
		},

		handleStepTwoNext() {
			// StepTwo组件已经通过@updateData事件更新了数据
			this.nextStep();
		},

		updateActivityData(data) {
			this.activityData = { ...this.activityData, ...data };
			
			// 如果更新的数据包含状态，同时更新activityState
			if (data.state !== undefined) {
				this.activityState = data.state;
				console.log('活动状态已更新为:', this.activityState);
				
				// 只有在编辑已存在活动时才根据状态调整步骤
				// 新建活动流程中不自动调整步骤
				if (this.activityId && this.current === 0) {
					// 如果是在第一步编辑已存在的活动，根据状态调整
					this.adjustStepByState();
				}
			}
			
			this.saveToCache();
		},

		updateFormCache(step, data) {
			this.formCache[step] = { ...this.formCache[step], ...data };
			this.saveToCache();
		},

		goToActivityList() {
			// 跳转到活动列表页面
			uni.showModal({
				title: '提示',
				content: '是否要离开当前页面？未保存的数据将会保留。',
				success: (res) => {
					if (res.confirm) {
						// 保存当前数据
						this.saveToCache();
						// 跳转到活动列表
						uni.navigateTo({
							url: '/pages/activity/release'
						});
					}
				}
			});
		},

		// 新建活动时从缓存恢复数据（但不恢复步骤状态）
		loadFromCacheForNewActivity() {
			try {
				const cacheData = uni.getStorageSync('launchevent_cache');
				if (cacheData && cacheData.timestamp) {
					// 检查缓存是否过期（24小时）
					const now = Date.now();
					const cacheAge = now - cacheData.timestamp;
					const maxAge = 24 * 60 * 60 * 1000; // 24小时

					if (cacheAge < maxAge) {
						// 只恢复表单数据，不恢复步骤状态
						this.formCache = cacheData.formCache || { stepOne: {}, stepTwo: {} };
						// 确保步骤保持为0（第一步）
						this.current = 0;
						console.log('新建活动：从缓存恢复表单数据，步骤保持第一步');
					} else {
						// 缓存过期，清除
						this.clearCache();
					}
				}
			} catch (e) {
				console.error('加载缓存失败:', e);
			}
		},

		// 编辑活动时从缓存恢复表单数据，不恢复活动ID和状态
		loadFromCacheForEdit() {
			try {
				const cacheData = uni.getStorageSync('launchevent_cache');
				if (cacheData && cacheData.timestamp) {
					// 检查缓存是否过期（24小时）
					const now = Date.now();
					const cacheAge = now - cacheData.timestamp;
					const maxAge = 24 * 60 * 60 * 1000; // 24小时

					if (cacheAge < maxAge) {
						// 只恢复表单数据，不恢复活动ID和状态
						this.formCache = cacheData.formCache || { stepOne: {}, stepTwo: {} };
						console.log('编辑活动：从缓存恢复表单数据，不恢复活动ID和状态');
					} else {
						// 缓存过期，清除
						this.clearCache();
					}
				}
			} catch (e) {
				console.error('加载缓存失败:', e);
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.launch-event {
	min-height: 100vh;
	background: #f5f5f5;
	padding-bottom: 120rpx;
}

.custom-navbar {
	background: #f5f5f5 !important;
}

/* 导航栏右侧样式 */
.navbar-right {
	display: flex;
	align-items: center;
	height: 100%;
}

.nav-icon {
	padding: 8rpx 16rpx;
	background: #0dc160;
	border-radius: 20rpx;
	margin-right: 16rpx;
}

.nav-text {
	font-size: 24rpx;
	color: #ffffff;
}

/* 进度指示器样式 */
.progress-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 32rpx;
	background: #ffffff;
	margin-bottom: 16rpx;
	border-radius: 8rpx;
	border: 1rpx solid #d5d5d5;
}

.progress-step {
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: 1;
	position: relative;
}

.progress-step:not(:last-child)::after {
	content: '';
	position: absolute;
	top: 18rpx;
	left: 60%;
	right: -40%;
	height: 2rpx;
	background: #d5d5d5;
	z-index: 1;
}

.progress-step.active:not(:last-child)::after,
.progress-step.completed:not(:last-child)::after {
	background: #0dc160;
}

.step-number {
	width: 36rpx;
	height: 36rpx;
	border-radius: 50%;
	background: #f5f5f5;
	color: #999;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: 500;
	margin-bottom: 8rpx;
	position: relative;
	z-index: 2;
	border: 2rpx solid #d5d5d5;
}

.progress-step.active .step-number {
	background: #0dc160;
	color: #ffffff;
	border-color: #0dc160;
}

.progress-step.completed .step-number {
	background: #0dc160;
	color: #ffffff;
	border-color: #0dc160;
}

.step-title {
	font-size: 22rpx;
	color: #999;
	text-align: center;
	line-height: 1.2;
}

.progress-step.active .step-title {
	color: #0dc160;
	font-weight: 500;
}

.progress-step.completed .step-title {
	color: #0dc160;
}

/* 步骤内容样式 */
.step-content {
	padding: 0 20rpx;
}

/* 表单容器样式 */
.form-container {
	background: #ffffff;
	border-radius: 8rpx;
	overflow: hidden;
	border: 1rpx solid #d5d5d5;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
	.progress-bar {
		padding: 20rpx 24rpx;
	}
	
	.step-number {
		width: 32rpx;
		height: 32rpx;
		font-size: 22rpx;
	}
	
	.step-title {
		font-size: 20rpx;
	}
}
</style>